# core/crud.py
import hashlib

from langserve import RemoteRunnable
from sqlalchemy.orm import Session, joinedload
from core.models import User, Conversation, ChatMessage


def create_user(db: Session, username: str, password: str):
    hashed_password = hashlib.md5(password.encode()).hexdigest()
    db_user = User(username=username, password=hashed_password)
    db.add(db_user)
    db.commit()
    db.refresh(db_user)
    return db_user


def user_detail_by_username(db: Session, username: str):
    return db.query(User).filter(User.username == username).first()


def user_detail_by_id(db: Session, user_id: int):
    return db.query(User).options(joinedload(User.department)).filter(
        User.user_id == user_id).first()


def create_conversation(conversation_id: str, db: Session, user_id: int):
    db_conversation = Conversation(conversation_id=conversation_id, user_id=user_id)
    db.add(db_conversation)
    db.commit()
    db.refresh(db_conversation)
    return db_conversation


def create_message(db: Session, conversation_id: str, user_id: int, message_content: str, sender: str):
    db_message = ChatMessage(conversation_id=conversation_id, user_id=user_id, message_content=message_content, sender=sender)
    db.add(db_message)
    db.commit()
    db.refresh(db_message)
    return db_message


def get_user(db: Session, user_id: int):
    return db.query(User).filter(User.id == user_id).first()


def get_conversation(db: Session, conversation_id: str):
    return db.query(Conversation).filter(Conversation.conversation_id == conversation_id).first()


def get_messages(db: Session, conversation_id: str):
    return db.query(ChatMessage).filter(ChatMessage.conversation_id == conversation_id).all()


def get_conversations_by_user_id(db: Session, user_id: int):
    return db.query(Conversation).filter(Conversation.user_id == user_id).all()
